// pages/homework-grading/homework-grading.js
const ocrService = require('../../utils/ocrService');
const aiGradingService = require('../../utils/aiGradingService');

Page({
  data: {
    selectedImage: null,
    isGrading: false,
    gradingResult: null,
    cameraContext: null,
    // 科目选择相关
    selectedSubject: '数学',
    selectedSubjectIndex: 1, // 默认选择数学，索引为1
    subjects: [
      { name: '语文', value: '语文' },
      { name: '数学', value: '数学' },
      { name: '英语', value: '英语' },
      { name: '物理', value: '物理' },
      { name: '化学', value: '化学' },
      { name: '生物', value: '生物' },
      { name: '历史', value: '历史' },
      { name: '地理', value: '地理' },
      { name: '政治', value: '政治' }
    ],
    showSubjectPicker: false,
    // 新增数据结构支持题目类型分组
    questionTypes: {
      fillInBlanks: {
        title: '填空题',
        score: 0,
        totalScore: 0,
        questions: []
      },
      calculations: {
        title: '口算题',
        score: 0,
        totalScore: 0,
        questions: []
      },
      computations: {
        title: '计算题',
        score: 0,
        totalScore: 0,
        questions: []
      },
      equations: {
        title: '解方程',
        score: 0,
        totalScore: 0,
        questions: []
      },
      wordProblems: {
        title: '应用题',
        score: 0,
        totalScore: 0,
        questions: []
      }
    }
  },

  onLoad(options) {
    console.log('作业批改页面加载', options);
    // 创建摄像头上下文
    this.cameraContext = wx.createCameraContext();
  },

  onShow() {
    console.log('作业批改页面显示');
    // 页面显示时自动初始化摄像头权限
    this.initializeCamera();
  },

  // 初始化摄像头
  initializeCamera() {
    // 检查摄像头权限
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.camera'] === false) {
          // 用户之前拒绝了摄像头权限，引导用户手动开启
          wx.showModal({
            title: '需要摄像头权限',
            content: '为了使用拍照功能，需要您授权摄像头权限',
            confirmText: '去设置',
            success: (modalRes) => {
              if (modalRes.confirm) {
                wx.openSetting({
                  success: (settingRes) => {
                    if (settingRes.authSetting['scope.camera']) {
                      console.log('摄像头权限已开启');
                    }
                  }
                });
              }
            }
          });
        } else if (res.authSetting['scope.camera'] === undefined) {
          // 用户还没有授权过，会在第一次调用时自动弹出授权
          console.log('摄像头权限未设置，将在拍照时请求');
        } else {
          // 用户已经授权
          console.log('摄像头权限已授权');
        }
      }
    });
  },

  // 返回上一页或重置到拍照界面
  goBack() {
    if (this.data.selectedImage && !this.data.gradingResult) {
      // 如果有选中的图片但没有批改结果，返回到拍照界面
      this.setData({
        selectedImage: null,
        gradingResult: null,
        isGrading: false
      });
    } else if (this.data.gradingResult) {
      // 如果有批改结果，返回到拍照界面
      this.setData({
        selectedImage: null,
        gradingResult: null,
        isGrading: false
      });
    } else {
      // 如果在拍照界面，返回上一页
      wx.navigateBack();
    }
  },

  // 摄像头错误处理
  onCameraError(e) {
    console.error('摄像头错误', e);
    wx.showToast({
      title: '摄像头启动失败',
      icon: 'error'
    });
  },

  // 图片加载错误处理
  onImageError(e) {
    console.error('图片加载错误', e);
    console.log('selectedImage:', this.data.selectedImage);
  },

  // 图片加载成功处理
  onImageLoad(e) {
    console.log('图片加载成功', e);
    console.log('图片路径:', this.data.selectedImage);
  },

  // 拍照
  takePhoto() {
    const that = this;
    
    // 检查摄像头权限
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.camera']) {
          // 请求摄像头权限
          wx.authorize({
            scope: 'scope.camera',
            success() {
              that.capturePhoto();
            },
            fail() {
              wx.showModal({
                title: '权限申请',
                content: '需要摄像头权限才能拍照，请在设置中开启',
                showCancel: false,
                confirmText: '去设置',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting();
                  }
                }
              });
            }
          });
        } else {
          that.capturePhoto();
        }
      }
    });
  },

  // 执行拍照
  capturePhoto() {
    const that = this;
    
    if (!this.cameraContext) {
      this.cameraContext = wx.createCameraContext();
    }
    
    this.cameraContext.takePhoto({
      quality: 'high',
      success(res) {
        console.log('拍照成功', res);
        that.setData({
          selectedImage: res.tempImagePath
        });
        
        wx.showToast({
          title: '拍照成功',
          icon: 'success'
        });
      },
      fail(err) {
        console.error('拍照失败', err);
        wx.showToast({
          title: '拍照失败，请重试',
          icon: 'error'
        });
      }
    });
  },

  // 从相册选择
  chooseFromAlbum() {
    const that = this;
    
    // 检查相册权限
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          // 请求相册权限
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              that.selectFromAlbum();
            },
            fail() {
              // 即使没有相册写入权限，也可以选择照片
              that.selectFromAlbum();
            }
          });
        } else {
          that.selectFromAlbum();
        }
      }
    });
  },

  // 执行相册选择
  selectFromAlbum() {
    const that = this;
    
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        console.log('选择照片成功', res);
        if (res.tempFiles && res.tempFiles.length > 0) {
          that.setData({
            selectedImage: res.tempFiles[0].tempFilePath
          });
          
          wx.showToast({
            title: '选择成功',
            icon: 'success'
          });
        }
      },
      fail(err) {
        console.error('选择照片失败', err);
        if (err.errMsg.indexOf('cancel') === -1) {
          wx.showToast({
            title: '选择照片失败',
            icon: 'error'
          });
        }
      }
    });
  },

  // 重新选择图片
  reselectImage() {
    this.setData({
      selectedImage: null,
      gradingResult: null,
      isGrading: false
    });
  },

  // 快速拍照（直接拍照不需要权限检查，因为已经在页面加载时检查过）
  quickTakePhoto() {
    this.capturePhoto();
  },

  // 重新拍照
  retakePhoto() {
    this.setData({
      selectedImage: null,
      gradingResult: null,
      isGrading: false
    });
  },

  // 添加底部操作按钮的方法
  onReGrade() {
    if (this.data.selectedImage) {
      this.startGrading();
    } else {
      wx.showToast({
        title: '请先选择图片',
        icon: 'none'
      });
    }
  },

  onSaveResult() {
    if (!this.data.gradingResult) {
      wx.showToast({
        title: '暂无批改结果',
        icon: 'none'
      });
      return;
    }

    wx.showToast({
      title: '保存成功',
      icon: 'success'
    });
  },

  onShareResult() {
    if (!this.data.gradingResult) {
      wx.showToast({
        title: '暂无批改结果',
        icon: 'none'
      });
      return;
    }

    wx.showShareMenu({
      withShareTicket: true,
      success: () => {
        console.log('分享成功');
      }
    });
  },

  onPrintResult() {
    if (!this.data.gradingResult) {
      wx.showToast({
        title: '暂无批改结果',
        icon: 'none'
      });
      return;
    }

    wx.showToast({
      title: '打印功能开发中',
      icon: 'none'
    });
  },

  // 开始批改
  startGrading() {
    console.log('开始批改，selectedImage:', this.data.selectedImage);
    if (!this.data.selectedImage) {
      wx.showToast({
        title: '请先选择图片',
        icon: 'error'
      });
      return;
    }

    this.setData({
      isGrading: true
    });

    // 执行OCR识别
    this.performOCR();
  },

  // 执行OCR识别
  performOCR() {
    const that = this;
    
    // 将图片转换为base64
    wx.getFileSystemManager().readFile({
      filePath: this.data.selectedImage,
      encoding: 'base64',
      success(res) {
        console.log('图片转base64成功');
        
        // 调用OCR服务
        ocrService.recognizeText(res.data)
          .then(ocrResult => {
            console.log('OCR识别成功', ocrResult);
            // 继续执行AI批改
            that.performAIGrading(ocrResult);
          })
          .catch(error => {
            console.error('OCR识别失败', error);
            that.setData({
              isGrading: false
            });
            wx.showToast({
              title: 'OCR识别失败',
              icon: 'error'
            });
          });
      },
      fail(err) {
        console.error('读取图片失败', err);
        that.setData({
          isGrading: false
        });
        wx.showToast({
          title: '读取图片失败',
          icon: 'error'
        });
      }
    });
  },

  // 执行AI批改
  performAIGrading(ocrResult) {
    const that = this;
    
    // 根据选择的科目设置不同的批改标准
    const gradingCriteria = this.getGradingCriteriaBySubject(this.data.selectedSubject);
    
    // 调用AI批改服务，传入OCR识别的原始文本
    aiGradingService.gradeWithAI(ocrResult.text, {
      subject: this.data.selectedSubject,
      gradingCriteria: gradingCriteria,
      useLocalAI: true
    })
      .then(result => {
        console.log('AI批改成功', result);
        
        if (result.success) {
          console.log('AI批改成功', result.data);
          
          // 处理AI分析数据，确保数组格式正确
          const processedResult = {
            ...result.data,
            // 确保strengths是数组格式
            strengths: Array.isArray(result.data.strengths) 
              ? result.data.strengths 
              : (result.data.strengths ? result.data.strengths.split('\n').filter(item => item.trim()) : []),
            // 确保weaknesses是数组格式  
            weaknesses: Array.isArray(result.data.weaknesses)
              ? result.data.weaknesses
              : (result.data.weaknesses ? result.data.weaknesses.split('\n').filter(item => item.trim()) : []),
            // 确保suggestions是数组格式
            suggestions: Array.isArray(result.data.suggestions)
              ? result.data.suggestions
              : (result.data.suggestions ? result.data.suggestions.split('\n').filter(item => item.trim()) : [])
          };
          
          // 判断是否有错题
          const hasWrongQuestions = that.checkHasWrongQuestions(processedResult);
          
          that.setData({
            isGrading: false,
            gradingResult: processedResult,
            hasWrongQuestions: hasWrongQuestions
          });
          
          console.log('批改完成，selectedImage:', that.data.selectedImage);
          console.log('批改完成，gradingResult:', that.data.gradingResult);
          
          wx.showToast({
            title: '批改完成',
            icon: 'success'
          });
        } else {
          throw new Error(result.error || '批改失败');
        }
      })
      .catch(error => {
        console.error('AI批改失败', error);
        that.setData({
          isGrading: false
        });
        wx.showToast({
          title: 'AI批改失败: ' + (error.message || error),
          icon: 'error'
        });
      });
  },

  // 检查是否有错题
  checkHasWrongQuestions(gradingResult) {
    // 检查填空题
    if (gradingResult.fillInBlanks && gradingResult.fillInBlanks.length > 0) {
      const hasWrongFillInBlanks = gradingResult.fillInBlanks.some(item => !item.isCorrect);
      if (hasWrongFillInBlanks) return true;
    }
    
    // 检查口算题
    if (gradingResult.calculations && gradingResult.calculations.length > 0) {
      const hasWrongCalculations = gradingResult.calculations.some(item => !item.isCorrect);
      if (hasWrongCalculations) return true;
    }
    
    // 检查计算题
    if (gradingResult.computations && gradingResult.computations.length > 0) {
      const hasWrongComputations = gradingResult.computations.some(item => !item.isCorrect);
      if (hasWrongComputations) return true;
    }
    
    // 检查解方程
    if (gradingResult.equations && gradingResult.equations.length > 0) {
      const hasWrongEquations = gradingResult.equations.some(item => !item.isCorrect);
      if (hasWrongEquations) return true;
    }
    
    // 检查应用题
    if (gradingResult.wordProblems && gradingResult.wordProblems.length > 0) {
      const hasWrongWordProblems = gradingResult.wordProblems.some(item => !item.isCorrect);
      if (hasWrongWordProblems) return true;
    }
    
    return false;
  },

  // 显示科目选择器
  showSubjectSelector() {
    this.setData({
      showSubjectPicker: true
    });
  },

  // 隐藏科目选择器
  hideSubjectSelector() {
    this.setData({
      showSubjectPicker: false
    });
  },

  // 选择科目
  onSubjectChange(e) {
    const index = e.detail.value[0]; // picker-view返回的是数组
    this.setData({
      selectedSubjectIndex: index
    });
    
    console.log('选择科目索引:', index);
  },

  // 确认选择科目
  confirmSubjectSelection() {
    const selectedSubject = this.data.subjects[this.data.selectedSubjectIndex].value;
    this.setData({
      selectedSubject: selectedSubject,
      showSubjectPicker: false
    });
    
    console.log('确认选择科目:', selectedSubject);
  },

  // 科目选择器取消
  onSubjectCancel() {
    this.setData({
      showSubjectPicker: false
    });
  },

  // 根据科目获取批改标准
  getGradingCriteriaBySubject(subject) {
    const criteriaMap = {
      '数学': '请仔细检查计算过程和答案的正确性，对于计算题要验证每一步骤',
      '语文': '请重点关注字词拼写、语法结构、表达准确性和文学理解',
      '英语': '请检查单词拼写、语法正确性、句式结构和语言表达',
      '物理': '请验证公式应用、计算过程和物理概念理解',
      '化学': '请检查化学方程式、化学计算和化学概念掌握',
      '生物': '请关注生物概念理解、实验分析和知识应用',
      '历史': '请评估历史事件理解、时间线掌握和史实准确性',
      '地理': '请检查地理知识掌握、地图分析和地理概念理解',
      '政治': '请评估政治理论理解、概念掌握和分析能力'
    };
    
    return criteriaMap[subject] || '请仔细检查答案的正确性和完整性';
  }
});